package com.chinatechstar.admin.service.impl;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.chinatechstar.account.entity.SysUserDetail;
import com.chinatechstar.admin.entity.SysUser;
import com.chinatechstar.admin.mapper.SysUserMapper;
import com.chinatechstar.component.commons.utils.CurrentUserUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinatechstar.admin.entity.SysUserGroup;
import com.chinatechstar.admin.mapper.SysUserGroupMapper;
import com.chinatechstar.admin.service.SysUserGroupService;
import com.chinatechstar.component.commons.result.PaginationBuilder;
import com.chinatechstar.component.commons.utils.SequenceGenerator;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * 业务逻辑实现层
 */
@Service
@Transactional
public class SysUserGroupServiceImpl implements SysUserGroupService {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final SequenceGenerator SEQUENCE_GENERATOR = new SequenceGenerator();

    @Autowired
    private SysUserGroupMapper sysUserGroupMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询所有数据
     */
    @Override
    public List<SysUserGroup> findSysUserGroupAll() {
        return sysUserGroupMapper.findSysUserGroupAll();
    }

    /**
     * 查询分页
     */
    @Override
    public Map<String, Object> findSysUserGroupByCondition(Integer currentPage, Integer pageSize, String name, String sorter) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        if (StringUtils.isNotBlank(sorter)) {
            String sort = sorter.substring(0, sorter.lastIndexOf('_'));
            String sequence = "ascend".equals(sorter.substring(sorter.lastIndexOf('_') + 1)) ? "ASC" : "DESC";
            paramMap.put("sort", sort);
            paramMap.put("sequence", sequence);
        } else {
            paramMap.put("sort", "createTime");
            paramMap.put("sequence", "DESC");
        }
        Page<Object> page = PageHelper.startPage(currentPage, pageSize);
        List<LinkedHashMap<String, Object>> resultList = sysUserGroupMapper.findSysUserGroupByCondition(paramMap);
        return PaginationBuilder.buildResult(resultList, page.getTotal(), currentPage, pageSize);
    }

    /**
     * 查询导出数据列表
     */
    @Override
    public List<LinkedHashMap<String, Object>> findSysUserGroupForExcel(Map<String, Object> paramMap) {
        return sysUserGroupMapper.findSysUserGroupByCondition(paramMap);
    }

    /**
     * 根据主键ID数据查询数据
     */
    @Override
    public SysUserGroup findSysUserGroupById(Long id) {
        return sysUserGroupMapper.findSysUserGroupById(id);
    }

    /**
     * 根据主键ID数组查询数据
     */
    @Override
    public List<SysUserGroup> findSysUserGroupByIds(Long[] ids) {
        return sysUserGroupMapper.findSysUserGroupByIds(ids);
    }

    /**
     * 查询用户组所有用户数据
     */
    @Override
    public Map<String, Object> findUserByUserGroupId(Integer currentPage, Integer pageSize, Long id) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", id);
        Page<Object> page = PageHelper.startPage(currentPage, pageSize);
        List<LinkedHashMap<String, Object>> resultList = sysUserGroupMapper.findUserByUserGroupId(paramMap);
        return PaginationBuilder.buildResult(resultList, page.getTotal(), currentPage, pageSize);
    }

    /**
     * 新增
     */
    @Override
    public void insertSysUserGroup(SysUserGroup sysUserGroup) {
        SysUser currUser = sysUserMapper.getUserByUsername(CurrentUserUtils.getOAuth2AuthenticationInfo().get("name"));

        sysUserGroup.setId(SEQUENCE_GENERATOR.nextId());
        sysUserGroup.setCreateName(currUser.getNickname());
        sysUserGroup.setCreateUsername(currUser.getUsername());
        sysUserGroupMapper.insertSysUserGroup(sysUserGroup);
        logger.info("已新增： {}", sysUserGroup.getId());
    }

    /**
     * 批量新增
     */
    @Override
    public void insertSysUserGroups(List<SysUserGroup> sysUserGroups) {
        SysUser currUser = sysUserMapper.getUserByUsername(CurrentUserUtils.getOAuth2AuthenticationInfo().get("name"));

        for (SysUserGroup sysUserGroup : sysUserGroups) {
            sysUserGroup.setId(SEQUENCE_GENERATOR.nextId());
            sysUserGroup.setCreateName(currUser.getNickname());
            sysUserGroup.setCreateUsername(currUser.getUsername());
        }
        sysUserGroupMapper.insertSysUserGroups(sysUserGroups);
    }

    /**
     * 编辑
     */
    @Override
    public void updateSysUserGroup(SysUserGroup sysUserGroup) {
        sysUserGroupMapper.updateSysUserGroup(sysUserGroup);
        logger.info("已编辑： {}", sysUserGroup.getId());
    }

    /**
     * 批量编辑
     */
    @Override
    public void updateSysUserGroups(List<SysUserGroup> sysUserGroups) {
        sysUserGroupMapper.updateSysUserGroups(sysUserGroups);
    }

    /**
     * 删除
     */
    @Override
    public void deleteSysUserGroupById(Long id) {
        // 首先删除关联表
        sysUserGroupMapper.deleteUserGroupUserById(id);
        sysUserGroupMapper.deleteSysUserGroupById(id);
    }

    /**
     * 批量删除
     */
    @Override
    public void deleteSysUserGroupByIds(Long[] ids) {
        sysUserGroupMapper.deleteSysUserGroupByIds(ids);
    }

    /**
     * 软删除
     */
    @Override
    public void softDeleteSysUserGroupById(Long id) {
//        SysUserGroup sysUserGroup = sysUserGroupMapper.findSysUserGroupById(id);
//        if (sysUserGroup != null) {
//            sysUserGroup.setSoftDelete(0);
//            sysUserGroupMapper.updateSysUserGroup(sysUserGroup);
//        }

    }

    /**
     * 批量软删除
     */
    @Override
    public void softDeleteSysUserGroupByIds(Long[] ids) {
//        List<SysUserGroup> sysUserGroups = sysUserGroupMapper.findSysUserGroupByIds(ids);
//
//        if (sysUserGroups.size() > 0) {
//            for (SysUserGroup sysUserGroup :sysUserGroups){
//                sysUserGroup.setSoftDelete(0);
//            }
//
//            sysUserGroupMapper.updateSysUserGroups(sysUserGroups);
//        }
    }

    /**
     * 批量将用户加入用户组
     */
    @Override
    public void insertUserToUserGroup(Long userGroupId, Long[] userId) {
        sysUserGroupMapper.deleteSysUserGroupById(userGroupId);
        for (Long uid : userId) {
            sysUserGroupMapper.insertUserGroupIdUserId(SEQUENCE_GENERATOR.nextId(), userGroupId, uid);
        }
    }
}
